package oot.activity;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import oot.data.JSonPaser;
import oot.data.Place;
import oot.tab.activity.R;
import oot.utils.StringUtil;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.SimpleAdapter;
import android.widget.Toast;

import com.facebook.android.Facebook;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;

public class FBConnect extends Activity {

	private Facebook facebook;
	private String appId = "225429780912342";
	private String appSec = "992fe560e3daad2b9b5b333814676ed9";
	private String accessToken;
	private Location location;
	protected LocationManager lm;
	protected MyLocationListener locationListener;
	protected ProgressDialog dialog;
	private Handler mHandler;
	private List<Map<String, ?>> listLocation = new LinkedList<Map<String,?>>();
	private static final String LOCATION_NAME = "Location Name";
	private static final String LOCATION_ADD = "Location Address";
	private ArrayList<Place> listNearPlaces;
	private static final int NUMBER_CHARACTER = 30;
	private PullToRefreshListView listview;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.locations);
		mHandler = new Handler();
		listview = (PullToRefreshListView) findViewById(R.id.list_locations);
		listview.getRefreshableView().setCacheColorHint(0);
		listview.getRefreshableView().setBackgroundResource(R.drawable.bgconor);
		listview.getRefreshableView().setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int position,
					long arg3) {
				// TODO Auto-generated method stub
				Log.e("Touch","Touch on : " + position);
				Log.e("Content",listNearPlaces.get(position-1).getName()+"  " + listNearPlaces.get(position-1).getCategory()+
						"  " + listNearPlaces.get(position-1).getCity());
			}
		});
		facebook = new Facebook(appId);
		facebook.setAccessExpires(0);
		getAccessToken();
		
	}
	
	@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        dialog.dismiss();
        getLocation();
    }
	
	public Map<String,?> createItem(String name, String address) {
		Map<String,String> item = new HashMap<String,String>();
		if(name != null){
			item.put(LOCATION_NAME, name);
		}else{
			item.put(LOCATION_NAME, "");
		}
		if(name != null){
			item.put(LOCATION_ADD, address);
		}else{
			item.put(LOCATION_ADD, "");
		}
		return item;
	}

	public void getLocation() {
		new Thread() {
			@Override
			public void run() {
				Looper.prepare();
				dialog = ProgressDialog.show(FBConnect.this, "","Fetching location ... ", false, true,new DialogInterface.OnCancelListener() {
							@Override
							public void onCancel(DialogInterface dialog) {
								showToast("Cannot fetching location");
							}
						});

				if (lm == null) {
					lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
				}

				if (locationListener == null) {
					locationListener = new MyLocationListener();
				}

				Criteria criteria = new Criteria();
				criteria.setAccuracy(Criteria.ACCURACY_COARSE);
				String provider = lm.getBestProvider(criteria, true);
				if (provider != null && lm.isProviderEnabled(provider)) {
					lm.requestLocationUpdates(provider, 1, 0, locationListener,Looper.getMainLooper());
				} else {
					
					new AlertDialog.Builder(FBConnect.this).setTitle("Alert").setMessage("Enable gps").setPositiveButton("GPS setting",
									new DialogInterface.OnClickListener() {
										@Override
										public void onClick(DialogInterface dialog,int which) {
											startActivityForResult(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS),0);
										}
									})
									.setNegativeButton("Cancel",new DialogInterface.OnClickListener() {
										@Override
										public void onClick(DialogInterface dialog,int which) {
											dialog.dismiss();
											FBConnect.this.finish();
										}
									}).show();

				}
				Looper.loop();
			}
		}.start();
	}

	class MyLocationListener implements LocationListener {

		@Override
		public void onLocationChanged(Location loc) {

			if (loc != null) {
				location = loc;
				
				lm.removeUpdates(this);
				Log.e("RET","Location getFB"+location.getLatitude());
				new Thread(new Runnable() {
					
					@SuppressLint("ParserError")
					@Override
					public void run() {
						listNearPlaces = getLocationFB(accessToken,""+ location.getLatitude(), "" + location.getLongitude(), "");
						Log.e("Size","SIZE: " + listNearPlaces.size());
						mHandler.post(new Runnable() {
							
							@Override
							public void run() {
								makeList();
							}
						});
					}
				}).start();
				
				
			} else {
				dialog.dismiss();
			}
		}

		@Override
		public void onProviderDisabled(String provider) {
		}

		@Override
		public void onProviderEnabled(String provider) {
		}

		@Override
		public void onStatusChanged(String provider, int status, Bundle extras) {
		}
	}

	public ArrayList<Place> getLocationFB(String accessTokenFB, String lat,
			String lon, String query) {
		ArrayList<Place> result = new ArrayList<Place>();
		if (lat != null && lon != null && lat.length() > 0 && lon.length() > 0) {
			Bundle params = new Bundle();
			if (!query.equals("")) {
				params.putString("q", query);
			}
			params.putString("type", "place");
			params.putString("center", lat + "," + lon);
			params.putString("distance", "2000");

			try {
				String resp = facebook.request("search", params, "GET");
				if (resp != null) {
					Log.d("Facebook-FbAPIs", "Got response: " + resp);
				}
				result = JSonPaser.getPlace(resp);
			} catch (FileNotFoundException e) {
				result = null;
			} catch (MalformedURLException e) {
				result = null;
			} catch (IOException e) {
				result = null;
			}
		}

		return result;
	}

	public void showToast(final String msg) {
		mHandler.post(new Runnable() {
			@Override
			public void run() {
				Toast toast = Toast.makeText(FBConnect.this, msg,
						Toast.LENGTH_LONG);
				toast.show();
			}
		});
	}

	public void getAccessToken() {
		String baseURL = "https://graph.facebook.com/oauth/access_token?client_id="+ appId
				+ "&client_secret="+ appSec+ "&grant_type=client_credentials";
		AsyncHttpClient client = new AsyncHttpClient();
		client.get(baseURL, new AsyncHttpResponseHandler(){
			@Override
			public void onSuccess(String acc) {
				// TODO Auto-generated method stub
				super.onSuccess(acc);
				Log.e("RES",acc);
				accessToken = acc.substring(acc.indexOf("=")+1);
				facebook.setAccessToken(accessToken);
				getLocation();
			}
		});
	}
	
	public void makeList() {
		
		for (int i = 0; i < listNearPlaces.size(); i++) {
			listLocation.add(createItem(StringUtil.validString(listNearPlaces.get(i).getName(),NUMBER_CHARACTER), listNearPlaces.get(i).getCity()));
		}
		if(listview != null){
			listview.getRefreshableView().setAdapter(new SimpleAdapter(FBConnect.this, listLocation, R.layout.locationitem,
				new String[]{LOCATION_NAME,LOCATION_ADD}, new int[]{R.id.locationName,R.id.locationAddress}));
		}
		dialog.dismiss();
	}
}
